package com.study.web;

import com.alibaba.fastjson.JSONObject;
import com.study.r.R;
import com.study.utils.SysUtils;
import io.swagger.annotations.Api;
import lombok.Data;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;

/**
 * @author study
 * @version 1.0
 * @date 2020/6/22 23:40
 */
@RestController
@RequestMapping("test")
@Api(tags = "test测试")
public class TestController {

    //https://www.cnblogs.com/tv151579/p/3145238.html
    //springMVC中的Controller里面定义全局变量
    private HashMap<String, String> datas = new HashMap<>(5);

    @GetMapping("map")
    public R set(String msg) {
        datas.put(msg, msg);
        return R.ok();
    }


    @GetMapping("getmap")
    public R get(String msg) {
        System.out.println(datas);
        datas.clear();
        return R.ok().data(msg, datas.get(msg));
    }

    @GetMapping("param")
    public void param(HttpServletRequest req, String type) {
        System.out.println(req.getParameter("code"));
        System.out.println(req.getParameter("name"));
        System.out.println(type);
        System.out.println(req.getParameter("type"));

    }

    //RequestBody接受前台的 json
    @PostMapping("ajax")
    public Long ajax(@RequestBody Ajax ajax) {
        System.out.println(ajax);
        return 1L;
    }
    @PostMapping("content")
    public R content(@RequestBody String content) throws UnsupportedEncodingException {
        System.out.println(URLDecoder.decode(content,"UTF-8"));
        return R.ok();
    }

    @PostMapping("ajaxfile")
    public Long ajaxFile(Ajax ajax,
                         @RequestParam(value = "fils", required = false) MultipartFile fils) {
        System.out.println(ajax);
        System.out.println(fils == null);
        try {
            fils.transferTo(new File("d:/", SysUtils.getDate4() + ".jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1L;
    }

    @PostMapping("ajaxform")
    public JSONObject ajaxFrom(@RequestParam(value = "fils", required = false) MultipartFile fils
            , Ajax ajax) {
        System.out.println(ajax);
        if (fils != null) {
            System.out.println(fils.getSize());
            try {
                fils.transferTo(new File("d:/", SysUtils.getDate4() + ".jpg"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", "成功");
        return jsonObject;
    }
}

@Data
class Ajax {
    private String study;
    private String age;
}
